from rest_framework import serializers
from .models import Order, Review
from accounts.models import User, Technician
from services.models import Service

class OrderSerializer(serializers.ModelSerializer):
    customer_name = serializers.CharField(source='customer.username', read_only=True)
    technician_name = serializers.CharField(source='technician.real_name', read_only=True)
    service_name = serializers.CharField(source='service.name', read_only=True)
    
    class Meta:
        model = Order
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'paid_at', 'completed_at']


class ReviewSerializer(serializers.ModelSerializer):
    customer_name = serializers.CharField(source='customer.username', read_only=True)
    technician_name = serializers.CharField(source='technician.real_name', read_only=True)
    order_id = serializers.IntegerField(source='order.id', read_only=True)
    
    class Meta:
        model = Review
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class CreateOrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ['technician', 'service', 'appointment_time', 'address', 'contact_person', 'contact_phone', 'remarks']
    
    def validate(self, data):
        # 验证技师是否存在且已认证
        technician = data['technician']
        if not technician.is_verified:
            raise serializers.ValidationError("技师未认证")
        
        # 验证服务是否存在且启用
        service = data['service']
        if not service.is_active:
            raise serializers.ValidationError("服务已停用")
        
        return data